package com.byron.media.server.client;

import com.byron.media.server.config.MediaServerConfig;
import com.byron.media.server.enums.Args;
import com.byron.media.server.handlers.SessionContainer;
import com.byron.media.server.model.MediaData;
import com.byron.media.server.model.MediaHeaderObj;
import com.byron.media.server.model.ProxyMediaData;
import com.byron.media.server.utils.JsonUtils;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;

@Slf4j
@ChannelHandler.Sharable
public class MediaClientHandler extends ChannelInboundHandlerAdapter {

    private SessionContainer sessionContainer;

    private MediaServerConfig mediaServerConfig;

    public MediaClientHandler(MediaServerConfig mediaServerConfig, SessionContainer sessionContainer) {
        this.sessionContainer = sessionContainer;
        this.mediaServerConfig = mediaServerConfig;
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        // 连上之后发送组名
//        ctx.writeAndFlush(mediaConfig.getGroup());

        MediaHeaderObj header = new MediaHeaderObj();
        header.getCmd().put("cmd", "reg");
        header.getCmd().put("respone", 0);
//        header.getArgs().put(Args.GROUP_NAME, mediaConfig.getGroup());
        header.getArgs().put(Args.PROXY, true);
//        header.getDevice().put("id", mediaConfig.getDevice());

        String json = JsonUtils.toJson(header);
        ctx.writeAndFlush(json);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        // 收到来自服务器的代理媒体数据
        if(msg instanceof ProxyMediaData){
            ProxyMediaData data = (ProxyMediaData) msg;
            // 推送到前端
            sessionContainer.sendToGroup(data.getGroupName(), data.getMediaData());

            if(mediaServerConfig.isBroadcastRtp() && data.getMediaData().isFromWireless()){
                sessionContainer.broadcastAsRtp(data.getGroupName(), data.getMediaData());
            }

        // TODO 理论上不会收到来自服务器的媒体数据
        } else if(msg instanceof MediaData){
            Assert.assertTrue("理论上不会收到来自服务器的媒体数据", false);
        } else if(msg instanceof String){
            String json = (String) msg;
            MediaHeaderObj header = JsonUtils.fromJson(json, MediaHeaderObj.class);

            if(header.getCmd() == null){
                return;
            }

            String cmd = (String) header.getCmd().get("cmd");
            if(cmd == null){
                return;
            }

            if(cmd.equals("unreg")){
                String groupName = (String) header.getArgs().getOrDefault(Args.GROUP_NAME, "");
                if("".equals(groupName)){
                    return;
                }
                boolean sender = (boolean) header.getArgs().getOrDefault(Args.SENDER, false);
                String device = (String) header.getDevice().get("id");
                log.info("主服务器客户端 " + device + "断开连接");
                if(sender){
                    sessionContainer.cleanIframe(groupName);
                }
            }
        }
        ctx.fireChannelReadComplete();
    }
}
